local skill = fk.CreateSkill {
  name = "hanqing__lianke__enemy_at_the_gates_skill",
}

Fk:loadTranslationTable{
  ["hanqing__lianke__enemy_at_the_gates_skill"] = "兵临城下",
}

skill:addEffect("cardskill", {
  mute = true,
  target_num = 1,
  mod_target_filter = function(self, player, to_select, selected)
    return to_select ~= player
  end,
  target_filter = Util.CardTargetFilter,
  on_effect = function(self, room, effect)
    local player = effect.from
    local to = effect.tos[1]
    local cards = {}
    local total = 4
    if effect.extra_data and effect.extra_data.num then
      total = total + effect.extra_data.num
      if total < 1 then return end
    end
    local damageDealt = false
    for _ = 1, total do
      local id = room:getNCards(1)[1]
      table.insert(cards, id)
      room:turnOverCardsFromDrawPile(player, {id}, "enemy_at_the_gates_skill", true)
      local card = Fk:getCardById(id)
      if card.trueName == "slash" and player:canUseTo(card, to, {bypass_distances = true, bypass_times = true}) then
        local use = {
          card = card,
          from = player,
          tos = {to},
          extraUse = true,
        }
        room:useCard(use)
        if use and use.damageDealt then
          damageDealt = true
        end
      end
    end
    local banner = room:getBanner("hanqing__lianke-phase") or {}
    if #banner > 0 then
      for _, id in ipairs(banner) do
        room:showCards(id)
        local card = Fk:getCardById(id)
        if card.trueName == "slash" and player:canUseTo(card, to, {bypass_distances = true, bypass_times = true}) and
          not player.dead and not to.dead then
          local use = {
            card = card,
            from = player,
            tos = {to},
            extraUse = true,
          }
          room:useCard(use)
          if use and use.damageDealt then
            damageDealt = true
          end
        end
      end
    end
    if damageDealt then
      if #cards > 0 then
        table.insertTableIfNeed(banner, cards)
        room:setBanner("hanqing__lianke-phase", banner)
      end
    else
      room:setBanner("hanqing__lianke-phase", {})
    end
    room:cleanProcessingArea(cards, "enemy_at_the_gates_skill")
  end,
})

return skill
